#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json

import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class ZhejiangJiaxingPolicy(BaseTaxPolicySpider):
    name = 'zhejiang_jiaxing_shownews_policy'

    province = '浙江省'
    city: str = "嘉兴市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                # "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 412],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['嘉兴市科学技术局', '', 'https://kjj.jiaxing.gov.cn/col/col1229562370/index.html'],
            ['嘉兴市科学技术局', '', 'https://kjj.jiaxing.gov.cn/col/col1229562371/index.html'],
            ['嘉兴市农业农村局', '', 'https://nyjjj.jiaxing.gov.cn/col/col1229397321/index.html'],
            ['嘉兴市商务局', '', 'https://swj.jiaxing.gov.cn/col/col1229455704/index.html'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        # print(params)
        elem_list = response.xpath("""//script""").re(r"urls\[i\]='(.*?)';")

        for elem in elem_list:
            item = Item()
            item['source_url'] = elem
            # item['title'] = elem.xpath(""".//a[@title]/@title""").get() or elem.xpath(""".//a//text()""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            print(item['source_url'])
            # item['publish_date'] = "-".join(elem.xpath("./div[@class='date']/text()").re(r"\d+"))
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            # print(params, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        # total_page = response.xpath(
        #     "//*[@class='pagebar' or contains(@class, 'p_next')]//a[contains(text(), '下页')]/@href").re_first(r"\d+")
        # next_url = response.xpath(
        #     "//*[@class='pagebar' or contains(@class, 'p_next')]//a[contains(text(), '下页')]/@href").get()
        # total_page = response.xpath("//span[@class='p_no']/a/text()").getall()[-1]
        # print(response.url, len(elem_list), 'next_url', next_url)
        # if next_url:
        #     meta.update({'item': prev_item})
        #     if meta.get("is_next") is not False:
        #         if int(total_page) > 10:
        #             meta.update({'is_next': False})
        #             for i in range(1, int(total_page) + 1):
        #                 next = next_url.replace(total_page, str(i))
        #                 yield response.follow(next, callback=self.parse_list, meta=meta)
        #         else:
        #             yield response.follow(next_url, callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl zhejiang_jiaxing_shownews_policy".split())
